package froxy.urlfetch;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.InputStreamEntity;

import froxy.client.Helper;

public class DirectPostUrlFetch extends DirectFetch {
    private static Log logger = LogFactory.getLog(DirectPostUrlFetch.class);

    @Override
    protected HttpUriRequest createRequest(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        url = addQueryString(request, url);

        logger.info(request.getRemoteAddr() + " posts " + url);
        url = base64URL(url);
        HttpPost httppost = new HttpPost(url);
        try {
            InputStream is = request.getInputStream();
            InputStreamEntity entity = new InputStreamEntity(is, this.getContentLength(request));
            httppost.setEntity(entity);
            return httppost;
        } catch (IOException e) {
            logger.error("Post Error", e);
            e.printStackTrace();
        }
        return httppost;
    }

    private int getContentLength(HttpServletRequest request) {
        int result = 0;
        String len = request.getHeader(Helper.Content_Length);
        if (len != null && !len.isEmpty()) {
            result = Integer.valueOf(len);
        }
        return result;
    }
}
